package com.todd.studentms.servlet;

import cn.hutool.Hutool;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.todd.studentms.entity.Grade;
import com.todd.studentms.entity.Person;
import com.todd.studentms.entity.vo.GradeJoinPersonJoinCourse;
import com.todd.studentms.service.impl.GradeServiceImpl;
import com.todd.studentms.util.Tdber;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.function.BiConsumer;

@WebServlet("/grade/*")
public class GradeServlet extends EssentialServlet {

    // /getgradebyperson
    public List<GradeJoinPersonJoinCourse> getgradebyperson(JSONObject jsonObj, HttpServletRequest req, HttpServletResponse res) throws Exception {
        return new GradeServiceImpl().getGradeByPerson(JSONUtil.toBean(jsonObj, Person.class));
    }

    // /add
    public boolean add(JSONObject jsonObj, HttpServletRequest req, HttpServletResponse res) {
        return new GradeServiceImpl().add(JSONUtil.toBean(jsonObj, Grade.class));
    }

    // /upd
    public boolean upd(JSONObject jsonObj, HttpServletRequest req, HttpServletResponse res) {
        return new GradeServiceImpl().update(JSONUtil.toBean(jsonObj, GradeJoinPersonJoinCourse.class));
    }

    // /getlike
    public List<GradeJoinPersonJoinCourse> getlike(JSONObject jsonObj, HttpServletRequest req, HttpServletResponse res) throws Exception {
        return new GradeServiceImpl().getLike(
                JSONUtil.toBean(jsonObj, GradeJoinPersonJoinCourse.class),
                jsonObj.getStr("personTypeId")
        );
    }

    // /del (注意这个不是DELETE请求, 而是POST, 因为不是按id删除)
    public boolean del(JSONObject jsonArr, HttpServletRequest req, HttpServletResponse res) {
        return jsonArr.getJSONArray("items")
                .stream()
                .map(o -> {
                    JSONObject item = (JSONObject) o;
                    return Tdber.runExecute(
                            "delete from `grade` where stu_id = ? and course_id = ?",
                            new Object[]{item.getStr("stuId"), item.getStr("courseId")});
                })
                .allMatch(o -> Boolean.TRUE.equals(o));
    }

}
